<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Uajax extends CF_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->library('form_validation');
		//$this->output->set_content_type('application/json');
		//$this->output->set_header('Content-type: application/json',true);
		$this->uid = $this->user_login->is_logged_in() ? $this->user_login->get_user_id() : 0;
		$this->username = $this->user_login->is_logged_in() ? $this->user_login->get_username() : '';
	}

	//验证用户名
	public function ajaxusername() {
		$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]|max_length[10]|callback_username_check');
		//$this->user_login->is_username_available($username);
		if ($this->form_validation->run())
		{
			$array = array(
				'status'	=>	'ERR',
				'data'		=>	0
			);
		}
		else
		{
			$array = array(
				'status'	=>	'OK',
				'data'		=>	1
			);
		}

        $this->output->set_output(json_encode($array));
	}

	//验证码
	public function ajaxcode() {
		$this->form_validation->set_rules('code', 'Code', 'trim|required|alpha_dash');
		//$this->user_login->is_username_available($username);
		if ($this->form_validation->run() == FALSE)
		{
			exit('0');
		}
		else
		{
			if($this->_is_captcha_match($this->form_validation->set_value('code')) )
			{
				exit('1');
			}
			else
			{
				exit('0');
			}
		}
	}

	//验证邮箱
	public function ajaxemail() {
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_email_check');
		if ($this->form_validation->run())
		{
			$array = array(
				'status'=>'OK',
				'data'=>'OK'
			);

		}
		else
		{
			$array = array(
				'status'=>'OK',
				'data'=>'ERR'
			);

		}


        $this->output->set_output(json_encode($array));
	}
	//获取食材信息
    public function getshicaiinfo($shicai_name = '') {
		$this->load->model('shicai_mdl');
		if ( $this->shicai_mdl->get_shicai_by_alias($shicai_name))
		{
			$data['shicai_info'] = $this->shicai_mdl->get_shicai_by_alias($shicai_name);
		}
		else
		{
			$data['shicai_info'] = FALSE;
		}
		$this->load->view('ajax/shicai_info',$data);

    }

    //喜欢/取消喜欢食材
    public function addDelLike() {
    	$this->load->model('user/user_like','ulike');
    	$this->load->model('shicai_mdl');
		$val = $this->form_validation;
		$val->set_rules('shicaiid', 'Shicaiid', 'trim|required|xss_clean');
		$val->set_rules('bools', 'Bools', 'trim|required|xss_clean');

		if ($this->uid == 0)
		{
			$data = 'LOGIN'; //未登录
		}
		else
		{
			if ( $val->run() AND $this->shicai_mdl->get_by(array('id'=>$val->set_value('shicaiid'))))
			{
				if ($val->set_value('bools') == 1)
				{
					if ( $this->ulike->get_shicai_like($val->set_value('shicaiid'), $this->uid) == 0 )
					{
						$this->ulike->add_shicai_like($val->set_value('shicaiid'), $this->uid);
						$data = 'OK';
					}
					else
					{
						$data = 'HAS'; //已关注，请不要重复关注
					}
				}
				else
				{
					$this->ulike->del_shicai_like($val->set_value('shicaiid'), $this->uid);
					$data = 'OK';
				}
			}
			else
			{
				$data = 'EMPTYINFO'; //食材不存在
			}
		}
		$array = array(
			'status'=>'OK',
			'data'=>$data
		);

        $this->output->set_output(json_encode($array));
    }

    //收藏/取消收藏菜谱
    public function addDelFav() {
    	$this->load->model('user/user_favorite','ufavorite');
    	$this->load->model('caipu_mdl');
		$val = $this->form_validation;
		$val->set_rules('cookid', 'Cookid', 'trim|required|xss_clean');
		$val->set_rules('status', 'Status', 'trim|required|xss_clean');

		if ($this->uid == 0)
		{
			$data = 'NoLogin'; //未登录
		}
		else
		{
			if ( $val->run() AND $this->caipu_mdl->get_by(array('id'=>$val->set_value('cookid'))))
			{
				if ($val->set_value('status') == 0)
				{
					if ( $this->ufavorite->get_caipu_favorite($val->set_value('cookid'), $this->uid) == 0 )
					{
						$this->ufavorite->add_caipu_favorite($val->set_value('cookid'), $this->uid);
						$data = 'OK';
					}
					else
					{
						$data = 'HAS'; //已收藏，请不要重复收藏
					}
				}
				else
				{
					$this->ufavorite->del_caipu_favorite($val->set_value('cookid'), $this->uid);
					$data = 'Success';
				}
			}
			else
			{
				$data = 'EMPTYINFO'; //菜谱不存在
			}
		}
		$array = array(
			'status'=>'OK',
			'data'=>$data
		);

        $this->output->set_output(json_encode($array));
    }

    //收藏/取消收藏菜单
    public function addDelCaidanfav() {
    	$this->load->model('user/user_favorite','ufavorite');
    	$this->load->model('caidan_mdl');
		$val = $this->form_validation;
		$val->set_rules('caidan_id', 'Caidan_id', 'trim|required|xss_clean');
		$val->set_rules('status', 'Status', 'trim|required|xss_clean');

		if ($this->uid == 0)
		{
			$data = 'NoLogin'; //未登录
		}
		else
		{
			if ( $val->run() AND $this->caidan_mdl->get_by(array('id'=>$val->set_value('caidan_id'))))
			{
				if ($val->set_value('status') == 0)
				{
					if ( $this->ufavorite->get_caidan_favorite($val->set_value('caidan_id'), $this->uid) == 0 )
					{
						$this->ufavorite->add_caidan_favorite($val->set_value('caidan_id'), $this->uid);
						$data = 'OK';
					}
					else
					{
						$data = 'HAS'; //已收藏，请不要重复收藏
					}
				}
				else
				{
					$this->ufavorite->del_caidan_favorite($val->set_value('caidan_id'), $this->uid);
					$data = 'Success';
				}
			}
			else
			{
				$data = 'EMPTYINFO'; //菜谱不存在
			}
		}
		$array = array(
			'status'=>'OK',
			'data'=>$data
		);

        $this->output->set_output(json_encode($array));
    }

    //点击菜单
    public function getcaidan() {
    	$this->load->model('user/user_caidan','ucaidan');
    	$this->load->model('caipu_mdl');
		$val = $this->form_validation;
		$val->set_rules('cookid', 'Cookid', 'trim|required|xss_clean');

		if ($this->uid == 0)
		{
			$data = 'NoLogin'; //未登录
		}
		else
		{
			if ( $val->run() AND $this->caipu_mdl->get_by(array('id'=>$val->set_value('cookid'))))
			{

				if ( $this->ucaidan->get_caidan_uid($this->uid)->num_rows() == 0 )
				{
					$data = '';
				}
				else
				{
					$caidanlist = '';
					$caidan_array = $this->ucaidan->get_caidan_uid($this->uid)->result_array();
					foreach( $caidan_array as $caidan ){
						$caidanlist.= '<li><input id="caidaninfo'.$caidan['id'].'" onclick="caidanInfo('.$caidan['id'].')" class="inp checkeding" name="caidan_id[]" type="checkbox" value="'.$caidan['id'].'" oldchecked> '.$caidan['title'].'</li>';
					}
					$data = $caidanlist; 
				}
			}
			else
			{
				$data = 'Nocook'; //菜谱不存在
			}
		}
		$array = array(
			'status'=>'OK',
			'data'=>$data
		);

        $this->output->set_output(json_encode($array));
    }

    //新建菜单
    public function addCaidanInfo() {
    	$this->load->model('user/user_caidan','ucaidan');
    	$this->load->model('caipu_mdl');
		$val = $this->form_validation;
		$val->set_rules('cookid', 'Cookid', 'trim|required|xss_clean');
		$val->set_rules('caidantitle', 'Caidantitle', 'trim|required|xss_clean');
		$val->set_rules('caidanjieshao', 'Caidanjieshao', 'trim|required|xss_clean');

		if ($this->uid == 0)
		{
			$data = 'NoLogin'; //未登录
		}
		else
		{
			if ( $val->run() AND $this->caipu_mdl->get_by(array('id'=>$val->set_value('cookid'))))
			{
				$caidan_id = $this->ucaidan->add_caidan_info($val->set_value('caidantitle'), $val->set_value('caidanjieshao'), $this->uid);
				$this->ucaidan->add_caidan_caipu($caidan_id, $val->set_value('cookid'), $this->uid);
				$data = 'OK';
			}
			else
			{
				$data = 'Nocook'; //菜谱不存在
			}
		}
		$array = array(
			'status'=>'OK',
			'data'=>$data
		);
        $this->output->set_output(json_encode($array));
    }

    //添加菜谱组信息 
    //暂理解为验证用
    public function getcaidanGroup(){
    	$this->load->model('user/user_caidan','ucaidan');
		$val = $this->form_validation;
		$val->set_rules('caidanid', 'Caidanid', 'trim|required|xss_clean');
		$val->set_rules('caipuid', 'Caipuid', 'trim|required|xss_clean');

    	if ( $val->run() AND $this->ucaidan->get_caidan_caipu($val->set_value('caidanid'), $val->set_value('caipuid'), $this->uid)->num_rows() == 0 )
		{
			$data = 'nodata';
		}
		else
		{
			$data = 'data'; 
		}
    	$array = array(
			'status'=>'OK',
			'data'=>$data
		);
        $this->output->set_output(json_encode($array));
    }
    //添加已经有的菜单信息
    public function addCaidanTitleInfo(){
    	$this->load->model('user/user_caidan','ucaidan');
    	$this->load->model('caipu_mdl');
		$val = $this->form_validation;
		$val->set_rules('cookid', 'Cookid', 'trim|required|xss_clean');
		$val->set_rules('arrnochecked', 'Arrnochecked', 'trim|xss_clean'); //未选中菜单ID数组
		$val->set_rules('arrchecked', 'Arrchecked', 'trim|xss_clean'); //选中菜单ID数组

		if ($this->uid == 0)
		{
			$data = 'NoLogin'; //未登录
		}
		else
		{
			if ( $val->run() AND $this->caipu_mdl->get_caipu_by_id($val->set_value('cookid')))
			{
				if ($val->set_value('arrchecked') && !$val->set_value('arrnochecked'))
				{
					$this->ucaidan->add_caidan_caipu($val->set_value('arrchecked'), $val->set_value('cookid'), $this->uid);
					$data = 'OK';
				}
				else
				{
					$data = 'Fail';
				}
			}
			else
			{
				$data = 'Nocook'; //菜谱不存在
			}
		}
		$array = array(
			'status'=>'OK',
			'data'=>$data
		);
        $this->output->set_output(json_encode($array));
    }

    //喜欢/取消喜欢食材
    public function addDelFriend() {
    	$this->load->model('user/user_guanzhu','uguanzhu');
    	$this->load->model('user/users','users');
		$val = $this->form_validation;
		$val->set_rules('userid', 'Userid', 'trim|required|xss_clean');
		$val->set_rules('info', 'Info', 'trim|required|xss_clean');
		$status = '-1';
		if ($this->uid == 0)
		{
			$flag = 'Nologin'; //未登录
		}
		else
		{
			if ( $val->run() AND $this->users->get_user_by_id($val->set_value('userid'))->num_rows() != 0)
			{
				if ($val->set_value('info') == 'add')
				{
					if ( $this->uguanzhu->get_user_guanzhu($val->set_value('userid'), $this->uid) == 0 )
					{
						$this->uguanzhu->add_user_guanzhu($val->set_value('userid'), $this->uid);
						$flag = 'Success';
						$status = '1';
					}
					else
					{
						$data = 'HAS'; //已关注，请不要重复关注
						$status = '1';
					}
				}
				else
				{
					$this->uguanzhu->del_user_guanzhu($val->set_value('userid'), $this->uid);
					$flag = 'Success';
					$status = '0';
				}
			}
			else
			{
				$flag = 'EMPTYINFO'; //用户不存在
			}
		}
		$array = array(
			'status'=>'OK',
			'data'=>array('flag' => $flag, 'status' => $status)
		);

        $this->output->set_output(json_encode($array));
    }
    //用户登录
	public function login() {
		$val = $this->form_validation;
		$val->set_rules('username', 'Username', 'trim|required|xss_clean');
		$val->set_rules('password', 'Password', 'trim|required|xss_clean');
		$val->set_rules('remember', 'Remember', 'integer');
		// 检查 登录尝试次数是否超过了在 配置文件中指定的值 并执行验证码
		if ($this->user_login->is_max_login_attempts_exceeded())
		{
			$val->set_rules('captcha', 'Confirmation Code', 'trim|required|xss_clean|callback_captcha_check');
		}

		if ($val->run() AND $this->user_login->login($val->set_value('username'), $val->set_value('password'), $val->set_value('remember')))
		{
			$data = array('status' => 'OK');
		}
		else
		{
			// 被踢用户
			if ($this->user_login->is_banned())
			{
				$data = array('status' => 'ERR_BANNED', 'data' => '帐号被禁用');
			}
			else
			{
				if ($this->user_login->_auth_error)
				{
					$data = array('status' => 'ERR', 'data' => $this->user_login->_auth_error);
				}
				else
				{
					// 如果登录尝试超过最大尝试配置 显示验证码
					if ($this->user_login->is_max_login_attempts_exceeded())
					{
						$data = array('status' => 'ERR_CAP', 'data' => '错误次数过多！请刷新网页');
					}
				}
			}
		}
		$this->output->set_output(json_encode($data));
    }
    
	public function ajaxregister()
	{		
		if ( ! $this->user_login->is_logged_in() AND $this->user_login->allow_registration)
		{	
			$val = $this->form_validation;
					
			$val->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[3]|max_length[10]|callback_username_check');
			$val->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[4]|max_length[20]');
			$val->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|callback_email_check');
			
			if ($this->user_login->captcha_registration)
			{
				$val->set_rules('captcha', 'captcha', 'trim|xss_clean|required|callback_captcha_check');
			}

			// Run form validation and register user if it's pass the validation
			if ($val->run() AND $this->user_login->register($val->set_value('username'), $val->set_value('password'), $val->set_value('email')))
			{	
				// Set success message accordingly
				if ($this->user_login->email_activation)
				{
					$data = array('status' => 'OK', 'data' => '您已经成功注册。检查您的电子邮件地址以激活您的帐户');
				}
				else
				{					
					$data = array('status' => 'OK');
				}
				//登录
				$this->user_login->login($val->set_value('username'), $val->set_value('password'), 0);
			}
			else
			{
				$data = array('status' => 'ERR', 'data' => $this->user_login->_auth_error);
			}
		}
		elseif ( ! $this->user_login->allow_registration)
		{
				$data = array('status' => 'ERR', 'data' => '禁止注册');
		}
		else
		{
			$data = array('status' => 'ERR', 'data' => '未登录');
		}

		$this->output->set_output(json_encode($data));
	}

	/* Callback function */
	
	public function username_check($username)
	{
		$result = $this->user_login->is_username_available($username);
		if ( ! $result)
		{
			$this->user_login->_auth_error = '用户名已经存在';
		}
				
		return $result;
	}

	public function email_check($email)
	{
		$result = $this->user_login->is_email_available($email);
		if ( ! $result)
		{
			$this->user_login->_auth_error = '电子邮件已经被另一个用户使用。';
		}
				
		return $result;
	}

	public function captcha_check($code)
	{
		$result = TRUE;

		list($usec, $sec) = explode(" ", microtime());
		$now = ((float)$usec + (float)$sec);	

		if (($this->session->userdata('captcha_time') + 180) < $now)
		{
			$this->user_login->_auth_error = '你的验证码已经过期。请再试一次。';		
			$result = FALSE;
		}
		elseif ( ! $this->_is_captcha_match($code))
		{
			$this->user_login->_auth_error = '验证码不正确。';		
			$result = FALSE;
		}

		return $result;
	}
	
	/* End of Callback function */

	public function upCookImageFile($uptype = '')
	{
		if (!$this->user_login->is_logged_in()) exit;
		$data = 0;
		if ($uptype == 'cover' || $uptype == 'setp')
		{
			$save_path = 'caipu_new/'. $uptype. '/' . date("Ymd", time()) .'/';
			$upload_path = '/uploads/'. $save_path;

			if ($uptype == 'cover')
			{
				$thumb_width = 600;
				$thumb_height = 400;
			}
			else
			{
				$thumb_width = 300;
				$thumb_height = 200;
			}

			if(!is_dir('.'.$upload_path)){
				mkdir('.'.$upload_path,0777);
			}

			$file_name = mt_rand(0,time());
			$config['upload_path'] = '.'.$upload_path;
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size'] = '1000';
			$config['file_name'] = $file_name.'.jpg';
			  
			$this->load->library('upload', $config);

			if ( ! $this->upload->do_upload('uploadFile'))
			{
				$data = array(
					'code' => 'ERR',
					'id' => 0,
					'upload' => $this->upload->display_errors(),
					'imgUrl' => '0'
				);
			} 
			else
			{
				$data = $this->upload->data();
				unset($config);
				//生成缩略图
				$config['image_library'] = 'gd2';
				$config['source_image'] = '.'.$upload_path.$file_name.'.jpg';
				$config['quality'] = '70';
				$config['create_thumb'] = TRUE;
				$config['maintain_ratio'] = TRUE;
				$config['width']  = $thumb_width;
				$config['height'] = $thumb_height;
				$this->load->library('image_lib', $config); 
				$this->image_lib->resize();
				unlink('.'.$upload_path.$file_name.'.jpg');
				//阿里云
				$this->load->library('alioss');
				$tmp_name = dirname(dirname(dirname(__FILE__)));
		        $content = '';
		        $length = 0;
		        $fp = fopen($tmp_name.$upload_path.$file_name.'_thumb.jpg','r');
		        if($fp)
		        {
		            $f = fstat($fp);
		            $length = $f['size'];
		            while(!feof($fp))
		            {
		                $content .= fgets($fp);
		            }
		        }
		        $upload_file_options = array('content' => $content, 'length' => $length);
				$upload_file_by_content = $this->alioss->upload_file_by_content('ichufang',$save_path.$file_name.'_thumb.jpg', $upload_file_options);
				//阿里云结束
				$insert_array = array(
					'location' => $save_path.$file_name.'_thumb.jpg',
					'time' => time(),
					'type' => $uptype,
					'uid' => $this->uid
				);
				$this->load->model('Attach_mdl');
				$insert_id = $this->Attach_mdl->caipu_attach_insert($insert_array);

				$data = array(
					'code' => 'Success',
					'id' => $insert_id,
					'upload' => $save_path.$file_name.'_thumb.jpg',
					'imgUrl' => base_url($upload_path.$file_name.'_thumb.jpg')
				);
			}
		}

		$this->output->set_output(json_encode($data));
	}

	public function _is_captcha_match($code)
	{
		return strtolower($code) == strtolower($this->session->userdata('captcha_word'));
	}

}

/* End of file uajax.php */
/* Location: ./application/controllers/uajax.php */